package com.guosen.zebra.framework.starter.ngx.internal.impl;



import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.guosen.zebra.framework.starter.ngx.exception.NgxException;
import com.guosen.zebra.framework.starter.ngx.model.DestroyParameter;
import com.guosen.zebra.framework.starter.ngx.model.InvokeContext;
import com.guosen.zebra.framework.starter.ngx.util.UrlEncodeDecoder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UniNgxDestroy {
    /**
     * 测试删除文件（夹）请求路径
     */
    private static final String DESTROY_PATH = "/UniExServices/restfulapi/%s/";

    public void execute(DestroyParameter destroyParameter, InvokeContext invokeContext) throws NgxException {
        String urlEncodeAccount = UrlEncodeDecoder.encode(invokeContext.getAccount());
        String url = invokeContext.getAddress() + String.format(DESTROY_PATH, urlEncodeAccount) + "?method=destroy";

        Map<String, String> parameters = buildParameters(destroyParameter);
        Map<String, String> headers = UniNgxUtil.buildHeaders(invokeContext);

        JsonNode result = UniNgxRestfulClient.post(url, headers, parameters);
        UniNgxUtil.raiseExceptionIfExist(result);
    }


    private Map<String, String> buildParameters(DestroyParameter destroyParameter) throws NgxException {
        Map<String, String> parameters = new HashMap<>();
        List<String> fsIdList = destroyParameter.getFsId();
        if (fsIdList != null && !fsIdList.isEmpty()) {
            ArrayNode children = UniNgxUtil.getObjectMapper().createArrayNode();
            for (String fsId : fsIdList) {
                ObjectNode fsIdJson = UniNgxUtil.getObjectMapper().createObjectNode();
                fsIdJson.put("fs_id", fsId);
                children.add(fsIdJson);
            }

            String childrenStr = null;
            try {
                childrenStr = UniNgxUtil.getObjectMapper().writeValueAsString(children);
            } catch (JsonProcessingException e) {
                throw new NgxException(e);
            }

            UniNgxUtil.addParameter(parameters, "children", childrenStr);
        }

        return parameters;
    }
}
